package com.dinadi.yidi.ui.activity;

import android.content.Intent;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.DailyProductBean;
import com.dinadi.yidi.bean.ImgsBean;
import com.dinadi.yidi.bean.ImgsRequest;
import com.dinadi.yidi.bean.IntegralBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.ui.view.FlyBanner;
import com.dinadi.yidi.ui.view.ShowImageWebView;
import com.dinadi.yidi.utils.Constant;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.ToastUtil;
import com.dinadi.yidi.utils.UtilPopupWindow;

import java.util.ArrayList;
import java.util.List;

/**
 * author: JiaYu.He
 * Date: 2017/12/6  积分好礼详情
 * Time: 14:48
 */

public class IntegralGiftActivity extends BaseActivity {
    private View view;
    private TextView product_title, product_price, tvTitle;
    private ImageView img_redeem_now;
    private FlyBanner design_view_pager;
    private ShowImageWebView activity_help_web;
    private String userId, token, productId, status;

    @Override
    protected View getLayout() {
        view = LayoutInflater.from(IntegralGiftActivity.this).inflate(R.layout.activity_integral_gift, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {

        changePager(2);
        tvTitle = (TextView) view.findViewById(R.id.text_title);
        tvTitle.setText(getResources().getString(R.string.text_product));
        design_view_pager = (FlyBanner) view.findViewById(R.id.design_view_pager);
        product_title = (TextView) view.findViewById(R.id.product_title);
        product_price = (TextView) view.findViewById(R.id.product_price);
        activity_help_web = (ShowImageWebView) view.findViewById(R.id.activity_help_web);
        img_redeem_now = (ImageView) view.findViewById(R.id.img_redeem_now);
        // 覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        activity_help_web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }

            // 网页加载结束
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                activity_help_web.getSettings().setJavaScriptEnabled(true);
                // web 页面加载完成，添加监听图片的点击 js 函数
                activity_help_web.setImageClickListner();
                //解析 HTML
                activity_help_web.parseHTML(view);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(IntegralGiftActivity.this, "请检查您的网络设置", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void initListener() {

        registerClickListener(img_redeem_now);
    }

    @Override
    protected void initData() {
        userId = SharePreferencesHelper.getInstance(IntegralGiftActivity.this).getString("userId");
        token = SharePreferencesHelper.getInstance(IntegralGiftActivity.this).getString("token");
        Intent intent = getIntent();
        productId = intent.getStringExtra("productId");
        getProduct();
    }

    @Override
    protected void clickEvent(View v) {

        switch (v.getId()) {
            case R.id.img_redeem_now:
                /*兑换好礼*/
                //   showPopupWindow();
                  /*"status": "状态【int】1-正常 2- 积分不足 3-商品已兑换完",*/
                if (status.equals("1")) {
                    exchange();
                } else if (status.equals("2")) {
                    ToastUtil.showToast("积分不足");
                } else {
                    ToastUtil.showToast("商品已兑换完");
                }

                break;
            default:
                break;
        }
    }

    private void exchange() {
        IntegralBean bean = new IntegralBean();
        bean.setUserId(userId);
        bean.setToken(token);
        bean.setProductId(productId);
        CommonInterface creativeProductInterface = new CommonInterface(IntegralGiftActivity.this, exchangeHttpListener);
        creativeProductInterface.getInterface("16044", JSON.toJSONString(bean));

    }

    private void showPopupWindow() {
        //当然是先初始化popupWindow
        final UtilPopupWindow popupWindow = new UtilPopupWindow();
        //我再工具中没有写构造函数，这里调用默认的构造函数
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        final int windowHeight = d.getHeight();
        //弹出框填充布局
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.popupwindow_exchange_integral, null);
        RelativeLayout layout2 = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_integral_gift, null);
        popupWindow.setPopupWindow(IntegralGiftActivity.this, windowHeight, layout, layout2, Gravity.CENTER);
        ImageView img_cancel = (ImageView) layout.findViewById(R.id.img_cancel);
        ImageView img_see_order = (ImageView) layout.findViewById(R.id.img_see_order);

        img_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        img_see_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showToast("查看订单");
            }
        });
    }

    /*产品详情*/
    private void getProduct() {
        DailyProductBean bean = new DailyProductBean();
        bean.setProductId(productId);
        bean.setToken(token);
        bean.setUserId(userId);
        CommonInterface dailyProductInterface = new CommonInterface(IntegralGiftActivity.this, httpListener);
        dailyProductInterface.getInterface("16043", JSON.toJSONString(bean));
    }

    /*兑换*/
    HttpListener exchangeHttpListener = new HttpListener() {

        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
//                showPopupWindow();
                ToastUtil.showToast("兑换成功");
                getProduct();
            } else {
                toast(errMsg);
            }


        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            changePager(1);
            closeLoadingDialog();
            toast("兑换失败");
        }
    };
    /*产品信息*/
    HttpListener httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            if (errCode.equals("0000")) {
                ImgsBean imgsBean = JsonUtil.parseJsonToBean(response, ImgsBean.class);

                ArrayList<ImgsRequest> dataList = new ArrayList<>();
                dataList.addAll(imgsBean.getImgs());

                final List<String> imgesUrl = new ArrayList<>();


                for (int i = 0; i < dataList.size(); i++) {

                    imgesUrl.add(dataList.get(i).getImgSrc());

                }
                design_view_pager.setImagesUrl(imgesUrl);


                design_view_pager.setOnItemClickListener(new FlyBanner.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        Intent intent = new Intent();
                        intent.putExtra(Constant.POSITION, position + "");
                        intent.putStringArrayListExtra(Constant.IMAGE_URL_ALL, (ArrayList<String>) imgesUrl);
                        intent.setClass(IntegralGiftActivity.this, ShowImageFromWebActivity.class);
                        startActivity(intent);

                    }
                });

                productId = JsonUtil.getFieldValue(response, "productId");
                String title = JsonUtil.getFieldValue(response, "title");
                product_title.setText(title);
                String point = JsonUtil.getFieldValue(response, "point");
                product_price.setText(point + "积分");
                String htmlPath = JsonUtil.getFieldValue(response, "htmlPath");
                activity_help_web.loadUrl(htmlPath);
                /*"status": "状态【int】1-正常 2- 积分不足 3-商品已兑换完",*/
                status = JsonUtil.getFieldValue(response, "status");
                if (status.equals("1")) {
                    img_redeem_now.setImageResource(R.drawable.icon_redeem_now);
                } else if (status.equals("2")) {
                    img_redeem_now.setImageResource(R.drawable.icon_redeem_insufficient);
                } else {
                    img_redeem_now.setImageResource(R.drawable.icon_redeem_finish);
                }

            } else {
                toast("获取信息失败");
            }
        }


        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            //    closeLoadingDialog();
            toast("获取信息失败");
        }

    };
}
